package hot

import "sort"

type Interval struct {
	Start, End int
}

func mergeIntervals(intervals []Interval) []Interval {
	if len(intervals) == 0 { //如果长度为0, 直接返回空数组即可
		return []Interval{}
	}

	sort.Slice(intervals, func(i, j int) bool { //根据起点对子数组进行排序
		return intervals[i].Start < intervals[j].Start
	})

	//声明解说数组
	res := make([]Interval, 0, len(intervals))
	res = append(res, intervals[0]) //0元素加入数组

	for i := 1; i < len(intervals); i++ { //1元素开始,遍历数组元素
		curRange := intervals[i]
		preRange := res[len(res)-1]

		if curRange.Start <= preRange.End {
			preRange.End = max(preRange.End, curRange.End)
		} else {
			res = append(res, curRange)
		}
	}

	return res
}
